<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
		<view class="back-btn" @click="backPage()">
			<view class="back-icon"></view>
		</view>
		<text class="title">收支明细</text>
		<view class="options-btn">
		<text class="dot"></text>
		<text class="dot"></text>
		<text class="dot"></text>
		</view>
    </view>
    
    <!-- 余额展示区 -->
    <view class="balance-area">
      <view class="balance-content">
        <!-- 左侧：当前余额 -->
        <view class="current-balance">
          <text class="balance-value">{{ balance }}</text>
          <text class="balance-label">当前现金余额（元）</text>
        </view>
        
        <!-- 中间：分隔线 -->
        <view class="balance-divider"></view>
        <!-- 右侧：累计数据 -->
        <view class="balance-stats">
          <view class="stat-item">
            <text class="stat-label">累计收入（元）：</text>
            <text class="stat-value">{{totalIncome}}元</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">累计提现（元）：</text>
            <text class="stat-value">{{totalWithdrawal}}元</text>
          </view>
        </view>
      </view>
      
      <!-- 提现按钮 -->
      <view class="withdraw-btn" @click="handleWithdraw">
        <text>提现</text>
      </view>
    </view>
    
    <!-- 收支明细列表 -->
    <view class="transaction-list">
      <view class="list-title">收支明细</view>
      
      <!-- 交易项目 -->
      <view class="transaction-item" v-for="(item, index) in transactionList" :key="index">
        <view class="transaction-info">
          <text class="transaction-name" v-text="item.name ? item.name : '提现'"></text>
          <text class="transaction-time">{{item.time}}</text>
        </view>
        <text class="transaction-amount" :class="{'income': item.type === 'income', 'expense': item.type === 'expense'}">
          {{item.type === 'income' ? '+' : '-'}} {{item.price || item.cashWithdrawal}}
        </text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import baseUrl from '../../utils/urlConfig.js';

const userInfo = uni.getStorageSync('info');
const balance = ref('');
const withdrawal = ref([]);
const records = ref([]);
const transactionList = ref([]); // 定义 transactionList 数组
//定义累计收入
const totalIncome = ref(0);
//定义累计提现
const totalWithdrawal = ref(0);
onMounted(() => {
  // 初始化数据
  fetchData();
})
function fetchData() {
  const request1 = new Promise((resolve) => {
    uni.request({
      url: baseUrl + '/yyq/withdrawal/listByMid/' + userInfo.mid,
      header: {
        Authorization: uni.getStorageSync('token')
      },
      success: res => {
        console.log('获取成功', res.data.data);
        // 筛选出审核状态为 2 的数据并赋值给 withdrawal
        withdrawal.value = res.data.data.filter(item => item.status === 2);
        resolve();
      },
    });
  });

  const request2 = new Promise((resolve) => {
    uni.request({
      url: baseUrl + '/yyq/record/listByMid/' + userInfo.mid,
      header: {
        Authorization: uni.getStorageSync('token')
      },
      success: res => {
        records.value = res.data.data;
        resolve();
      },
    });
  });

  const request3 = new Promise((resolve) => {
    uni.request({
      url: baseUrl + '/yyq/balance/listByMid/' + userInfo.mid,
      header: {
        Authorization: uni.getStorageSync('token')
      },
      success: res => {
        balance.value = res.data.data[0].initialBalance;
        resolve();
      },
    });
  });

Promise.all([request1, request2, request3]).then(() => {
  // 处理提现数据，添加 type 字段
  const processedWithdrawal = withdrawal.value.map(item => ({
    ...item,
    type: 'expense', // 更改为与模板中类名一致的值
    time: item.withdrawalTime
  }));
  const processedRecords = records.value.map(item => ({
    ...item,
    type: 'income', // 更改为与模板中类名一致的值
    time: item.time // 确保 records 数据也有 time 字段，避免排序时出错
  })); // 原代码此处缺少分号

  // 合并数据
  const combinedList = [...processedWithdrawal, ...processedRecords]; // processedRecords 已经是数组，不需要 .value

  // 按照时间排序
  const sortedList = combinedList.sort((a, b) => {
    const timeA = new Date(a.time);
    const timeB = new Date(b.time);
    if (isNaN(timeA.getTime()) || isNaN(timeB.getTime())) {
      console.error('时间格式错误，无法排序', a.time, b.time);
      return 0;
    }
    return timeB - timeA; // 降序排序，最新的时间在前面
  });

  // 确保 transactionList 已定义
  if (typeof transactionList === 'undefined') {
    console.error('transactionList 未定义');
    return;
  }
  transactionList.value = sortedList;
  sortedList.forEach(item => {
      const amount = Number(item.price || item.cashWithdrawal || 0);
      if (item.type === 'income') {
        totalIncome.value += amount;
      } else if (item.type === 'expense') {
        totalWithdrawal.value += amount;
      }
    });
  console.log('合并后的交易列表', transactionList.value);
});
}

// 返回上一页
function backPage(){
	uni.navigateBack()
}

// 处理提现
const handleWithdraw = () => {
  uni.showToast({
    title: '正在跳转到提现页面',
    icon: 'none'
  });
  uni.navigateTo({
  	url:'/pages/index/shouzhimingxi/tixian/tixian'
  })
};
</script>

<style>
/* 引入图标库 */
@import "/static/customicons.css";

/* 容器样式 */
.container {
  min-height: 100vh;
  background-color: #f6f6f6;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
  background-color: #2196F3;
  color: #ffffff;
  padding: 0 15px;
  position: relative;
}

.back-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.options-btn {
  display: flex;
  align-items: center;
}

.dot {
  width: 4px;
  height: 4px;
  background-color: #fff;
  border-radius: 50%;
  margin: 0 2px;
}

/* 图标样式 */
.iconfont {
  font-family: "customicons";
  font-size: 24px;
  color: #ffffff;
}

/* 余额展示区 */
.balance-area {
  background: linear-gradient(to bottom, #2196F3, #1E88E5);
  color: #ffffff;
  padding: 20px 15px;
}

.balance-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  position: relative;
}

.current-balance {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.balance-value {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 5px;
}

.balance-label {
  font-size: 14px;
  opacity: 0.9;
}

.balance-divider {
  width: 1px;
  height: 60px;
  background-color: rgba(255, 255, 255, 0.3);
  margin: 0 15px;
}

.balance-stats {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.stat-value {
  font-size: 14px;
  font-weight: bold;
}

.withdraw-btn {
  width: 180px;
  height: 40px;
  background-color: #FF5722;
  color: white;
  border-radius: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  margin: 20px auto 0;
}

/* 交易列表 */
.transaction-list {
  background-color: #ffffff;
  border-radius: 12px 12px 0 0;
  margin-top: -10px;
  padding: 15px;
  min-height: 300px;
}

.list-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-left: 5px;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 5px;
  border-bottom: 1px solid #f0f0f0;
}

.transaction-info {
  display: flex;
  flex-direction: column;
}

.transaction-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.transaction-time {
  font-size: 12px;
  color: #999;
}

.transaction-amount {
  font-size: 16px;
  font-weight: bold;
}

.income {
  color: #FF5722;
}

.expense {
  color: #4CAF50;
}

.back-btn{ margin-left: 20rpx; width: 50rpx; height: 50rpx; position: relative;}	
.back-icon { width: 30px; height: 30px;}	
.back-icon::before { content: ""; position: absolute; width: 20px; height: 2px; background-color: #fff; top: 15rpx; left: 47rpx; transform: translate(-50%, -50%); }
.back-icon::after { content: ""; position: absolute; width: 10px; height: 10px; border-left: 2px solid #fff; border-bottom: 2px solid #fff; transform: rotate(45deg); top: 5rpx; left: 30rpx;}	     
</style>
